# http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html

import win32file
import win32con

class Monitor:
    def __init__(self, path, pattern, recursive=True):
        self.path = path
        self.pattern = pattern
        self.recursive = recursive

        FILE_LIST_DIRECTORY = 0x0001
        self.hDir = win32file.CreateFile(
            path,
            FILE_LIST_DIRECTORY,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
        )

    def changed(self):
        results = win32file.ReadDirectoryChangesW(
            self.hDir, 1024, self.recursive, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None)
        for action, fn in results:
            if self.pattern.search(fn):
                return True
        return False

def mainloop(path, pattern, callback, recursive=True):
    monitor = Monitor(path, pattern, recursive=recursive)
    callback()
    while 1:
        if monitor.changed():
            callback()
